package org.example.springoauth2.securitycommon.service;

import lombok.extern.slf4j.Slf4j;
import org.example.springoauth2.securitycommon.entity.JdbcUser;
import org.example.springoauth2.securitycommon.entity.SysUser;
import org.example.springoauth2.securitycommon.factory.SysUserFactory;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.UUID;

/**
 * @author hzq
 * @date 2021/9/11 15:49
 */
@Slf4j
public class SysUserService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            // 如果是uuid则是刷新token 反之则是用户名密码登录
            UUID.fromString(username);
            // 刷新 token username=SysUser.unionId
            JdbcUser jdbcUser = SysUserFactory.queryJdbcUser(username);
            if (jdbcUser == null) {
                throw new UsernameNotFoundException("用户不存在");
            }
            jdbcUser.setAuthorities(AuthorityUtils.NO_AUTHORITIES);
            return new SysUser(jdbcUser);
        } catch (IllegalArgumentException ignored) {
            // 用户名 密码登录
            return loadUserByAuthType(SysUserFactory.AUTH_TYPE[0], username);
        }
    }

    /**
     * 抖音小程序登录
     *
     * @param openid 抖音openid
     */
    public UserDetails loadUserByTtOpenid(String openid) {
        return loadUserByAuthType(SysUserFactory.AUTH_TYPE[3], openid);
    }

    /**
     * 微信小程序登录
     *
     * @param openid 小程序openid
     */
    public UserDetails loadUserByWxOpenid(String openid) {
        return loadUserByAuthType(SysUserFactory.AUTH_TYPE[2], openid);
    }

    /**
     * 手机号码登录
     *
     * @param phone 手机号码
     */
    public UserDetails loadUserByPhone(String phone) {
        return loadUserByAuthType(SysUserFactory.AUTH_TYPE[1], phone);
    }

    protected UserDetails loadUserByAuthType(String authType, String key) {
        JdbcUser jdbcUser = SysUserFactory.queryJdbcUser(authType, key);
        if (jdbcUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        jdbcUser.setAuthorities(AuthorityUtils.NO_AUTHORITIES);
        log.info("登录成功:{}", jdbcUser);
        return new SysUser(jdbcUser);
    }
}
